/**
 * MUGGLE 工具类
 */
(function(window, document) {
    "use strict"
    "fuck IE"

    function Muggle() {}

    // 选取单元素
    Muggle.prototype.gets = function(dom) {
        var node = document.querySelector(dom);
        node.attr = function(method, set) {
            if (set == "undefined" || set == null) {
                return this.attributes[method].nodeValue;
            }
            return this.setAttribute(method, set);
        };
        return node;
    };
    // 选取多元素
    Muggle.prototype.getAll = function(dom) {
        return document.querySelectorAll(dom);
    };

    // 检测是否为空
    Muggle.prototype.empty = function(test) {
        if (
            (test == "") ||
            (test == null) ||
            (test == "undefined")
        ) {
            return true;
        }
        return false;
    }
    // 返回选中的radio对象, 如果没有则返回 null
    Muggle.prototype.checkedRadio = function(name) {
        var radio = Muggle.prototype.getAll('[name="'+name+'"]')
        for (var once in radio) {
            if (radio[once].checked) return radio[once];
        }
        return null;
    }

    /**
     * 请求方法(赞不支持jsonp)
     * @param json:
     *        json.method 请求方法(GET, POST)不区分大小写
     *        json.data 请求数据, 键值对格式
     *        json.url 请求地址(不支持跨域)
     *        json.progress 请求过程接口, 接收一个函数或false或不传值
     *        json.cookie 是否携带 cookie, 接收一个布尔值
     *        json.type 期望应答的数据格式，一般为json
     *        json.headers 以键值对格式设置请求头
     *        json.success 应答成功的回调函数
     *        json.faild 应答失败或超时的回调函数
     *        json.lock 锁类型 一次性锁(ONE) 交互锁(ITR) 无锁(不传)默认无锁
     */
    Muggle.prototype.Net = function(json) {
        var cmd = "";  // 请求串
        var xhr;  // 请求功能对象
        var method = json.method.toUpperCase();  // 请求方式
        if (window.XMLHttpRequest)
            var xhr = new XMLHttpRequest();
        else
            var xhr = new ActiveXObject("Microsoft.XMLHTTP");
        
        xhr.onerror = function(e) {
            json.faild(e);
        };
        xhr.ontimeout = function(e) {
            json.faild(e);
        }
        // 请求过程接口
        xhr.onprogress = json.progress ? json.progress : false;
        var data = json.data;
        if (data != "undefine" && data != false && data != null && data != "") {
            for (var key in json.data) {
                cmd += "&"+key+"="+json.data[key];
            }
            cmd = cmd.substr(1);  // 请求串拼接完成
        }
        if (method == "GET") {
            var index_swap;
            if ((index_swap = json.url.indexOf("?")) < 0) {
                if (!/\/$/.test(json.url)) {
                    json.url = json.url+"/";
                }
                json.url = json.url+"?"+cmd;
            } else {
                json.url = json.url+"&"+cmd;
                var swap_front = json.url.substr(0, index_swap);
                var swap_end = json.url.substr(index_swap);
                json.url = swap_front + "/" + swap_end
            }
        } else {
            var index_swap;
            if ((index_swap = json.url.indexOf("?")) < 0) {
                if (!/\/$/.test(json.url)) {
                    json.url = json.url+"/";
                }
            } else {
                if (json.url[index_swap-1] != "/") {
                    var swap_front = json.url.substr(0, index_swap);
                    var swap_end = json.url.substr(index_swap);
                    json.url = swap_front + "/" + swap_end;
                }
            }
        }
        console.log(json.url);
        xhr.open(method, json.url, true);  // 打开套接字
        try {
            xhr.withCredentials = json.cookie === true ? true : false;
        } catch (e) {
            xhr.withCredentials = false;
        }
        // 请求头信息设置
        var defaultType = "application/x-www-form-urlencoded;charset=UTF-8";
        xhr.setRequestHeader("Content-Type", defaultType);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.responseType = json.type ? json.type: "text";
        for (var key in json.headers) {
            xhr.setRequestHeader(key, json.headers[key]);
        }
        // 发送请求
        if (method == "GET") {
            xhr.send(null);  // 不带请求串的发送
        } else {
            xhr.send(cmd);  // 带请求串发送
        }

        // 接受应答
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var calldata = xhr.response ? xhr.response : xhr.responseText;
                    return json.success(calldata);
                }
            }
        }
    };

    // 文件切片上传
    Muggle.prototype.AjaxFile = function(json) {
        console.log("Muggle::AjaxFile:  正在执行...");
        var form = document.createElement("form");
        form.type = "file";
        form.enctype = "multipart/form-data";
        var formData = new FormData();
        var fd = document.createElement("input");
        fd.type = "file";
        fd.onchange = function() {
            var filedata = fd.files[0];
            if (filedata.type.indexOf(json.type) < 0) {
                alert("文件类型不正确，请重新选择~");
                return -1;
            }
            formData.append(json.sign, filedata);
            formData.append('fix', filedata.name.split(".").pop());
            formData.append('sign', json.sign);
            var xhr = new XMLHttpRequest();
            xhr.responseType = 'json';
            xhr.open("POST", json.url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        var calldata = xhr.response ? xhr.response : xhr.responseText;
                        json.success(calldata);
                        console.log("Muggle::AjaxFile:  执行完毕");
                        return 0;
                    }
                }
            }
            xhr.send(formData);
        };
        fd.click();
    }

    // 内存空间存储
    function db() {
        var dbThat = {};  // this缓存
        dbThat.dbase = {};  // 存储对象
        dbThat.dbForm = null;  // 当前选中的表
        // 初始化表
        this.link = function(form) {
            var stt = false;
            for (var swap_form in dbThat.dbase) {
                // 如果有表则选中
                if (swap_form == form) {
                    stt = true;
                    break;
                }
            }
            // 无表则初始化表
            if (! stt) {
                dbThat.dbase[form] = {};
            }
            dbThat.dbForm = form;
        };
        // 插入数据
        this.insert = function(key, val) {
            if (dbThat.dbForm == null) {
                throw new Error("您尚未未初始化数据表");
            }
            if (Muggle.prototype.empty(dbThat.dbase[dbThat.dbForm][key])) {
                dbThat.dbase[dbThat.dbForm][key] = [];
                dbThat.dbase[dbThat.dbForm][key].push(val);
                return true;
            }
            dbThat.dbase[dbThat.dbForm][key].push(val);
        };
        // 更新数据
        this.update = function(key, val) {
            if (dbThat.dbForm == null) {
                throw new Error("您尚未未初始化数据表");
            }
            delete dbThat.dbase[dbThat.dbForm][key];
            dbThat.dbase[dbThat.dbForm][key] = [];
            dbThat.dbase[dbThat.dbForm][key].push(val);
            return true;
        };
        // 删除数据
        this.delete = function(key) {
            if (dbThat.dbForm == null) {
                throw new Error("您尚未未初始化数据表");
            }
            if (! Muggle.prototype.empty(dbThat.dbase[dbThat.dbForm][key])) {
                delete dbThat.dbase[dbThat.dbForm][key];
            }
            return true;
        };
        this.select = function(key) {
            if (dbThat.dbForm == null) {
                throw new Error("您尚未未初始化数据表");
            }
            if (! Muggle.prototype.empty(dbThat.dbase[dbThat.dbForm][key])) {
                return dbThat.dbase[dbThat.dbForm][key];
            }
            return null;
        };
        this.drop = function() {
            delete dbThat.dbase[dbThat.dbForm];
            dbThat.dbForm = null;
        };
        this.desc = function() {
            delete dbThat.dbase;
            dbThat.dbForm = null;
        };

        this.show = function() {
            console.log(dbThat.dbase[dbThat.dbForm]);
        }
    }
    Muggle.prototype.catch = new db;

    window.Muggle = new Muggle;
})(window, document);